/*
 * @Date         : 2024-05-17 11:41:14 星期5
 * @Author       : xut
 * @Description  :
 */
import { Prisma, User } from "@prisma/client"
import { envConfig } from "../config/default"
import { redisClient } from "../utils/connectRedis"
import { prisma } from "../utils/prisma"
import { signJwt } from "../utils/jwt"

export async function createUser(input: Prisma.UserCreateInput) {
  return (await prisma.user.create({ data: input })) as User
}

export async function findUser(
  where: Partial<Prisma.UserCreateInput>,
  select?: Prisma.UserSelect
) {
  return await prisma.user.findFirst({ where, select })
}

export async function findUniqueUser(
  where: Prisma.UserWhereUniqueInput,
  select?: Prisma.UserSelect
) {
  return await prisma.user.findUnique({ where, select })
}

export async function findAllUsers({
  page_size,
  page_no,
  select,
}: {
  page_size: number
  page_no: number
  select?: Prisma.UserSelect
}) {
  const take = page_size || 10
  const skip = (page_no - 1) * take

  return (await prisma.user.findMany({ select, skip, take })) as User[]
}

export async function updateUser(
  where: Prisma.UserWhereUniqueInput,
  data: Prisma.UserUpdateInput,
  select?: Prisma.UserSelect
) {
  return await prisma.user.update({ where, data, select })
}

export async function deleteUser(where: Prisma.UserWhereUniqueInput) {
  return await prisma.user.delete({ where })
}

export async function signTokens(user: Prisma.UserCreateInput) {
  // 1. 创建 Session
  redisClient.set(`${user.id}`, JSON.stringify(user), {
    EX: envConfig.redisCacheExpiresIn * 60,
  })

  // 2. 生成 access_token 和 refresh_token
  const access_token = await signJwt(
    { sub: user.id },
    "accessTokenPrivateKey",
    {
      expiresIn: `${envConfig.accessTokenExpiresIn}m`,
    }
  )
  const refresh_token = await signJwt(
    { sub: user.id },
    "refreshTokenPrivateKey",
    {
      expiresIn: `${envConfig.refreshTokenExpiresIn}m`,
    }
  )

  return { access_token, refresh_token }
}
